package com.example.rbacmanage.handler;

import com.alibaba.druid.support.json.JSONUtils;
import com.example.rbacmanage.common.Constant;
import com.example.rbacmanage.entity.system.UserLog;
import com.example.rbacmanage.mapper.system.UserLogMapper;
import com.example.rbacmanage.util.JwtTokenUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserLogMapper userLogMapper;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        if (token == null || token.equals("") ) {
            Map<String,Object> map = new HashMap<>();
            map.put("code",401);
            map.put("msg","token is null");
            map.put("data",null);
            response.getWriter().write(JSONUtils.toJSONString(map));
            response.flushBuffer();
            return;
        }
        String username = JwtTokenUtil.getUsernameFromToken(token);
        if (username != null && JwtTokenUtil.validateToken(token,username))   {
            SecurityContextHolder.clearContext();
            redisTemplate.delete(Constant.systemLoginUserToken+username);

            UserLog userLog = new UserLog();
            userLog.setIp(null);
            userLog.setOperType("退出");
            userLog.setOperTime(new Date());
            userLog.setOperName(username);
            userLog.setCreateBy(username);
            userLog.setCreateTime(new Date());
            userLogMapper.insert(userLog);
        }else{
            Map<String,Object> map = new HashMap<>();
            map.put("code",403);
            map.put("msg","token is invalid");
            map.put("data",null);
            response.getWriter().write(JSONUtils.toJSONString(map));
            response.flushBuffer();
            return;
        }

        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","退出成功");
        response.getWriter().write(JSONUtils.toJSONString(map));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().flush();
    }
}
